import { _decorator, Component, director, EditBox, Node, Scene } from 'cc';
import { NetworkManager } from '../Global/NetworkManager';
import { ApiMsgEnum } from '../Common';
import DataManager from '../Global/DataManager';
import { SceneEnum } from '../Enum';
const { ccclass, property } = _decorator;

@ccclass('LoginManager')
export class LoginManager extends Component {
    input:EditBox;//输入框
    protected onLoad(): void {
        this.input = this.node.getComponentInChildren(EditBox);
        director.preloadScene(SceneEnum.Hall);// 预加载场景
    }

    protected async start(): Promise<void> {
        await NetworkManager.Instance.connect()
    }

    async handleClick(){
        if(!NetworkManager.Instance.isConnected){
            console.error("未连接");
            await NetworkManager.Instance.connect();
            return;
        }

        const nickname=this.input.string;
        if(!nickname){
            console.error("请输入昵称");
            return;
        }
        const {success,error,res}=await NetworkManager.Instance.callApi(ApiMsgEnum.ApiPlayerJoin,{
            nickname
        })
        if(!success){
            console.error("连接失败"+error);
            return;
        }
        DataManager.Instance.myPlayerId=res.player.id;
        console.log("连接成功 res"+res);
        director.loadScene(SceneEnum.Hall);//切换场景
    }
}

